//
//  HHFormTextFieldCell.m
//  Pod
//
//  Created by chun.chen on 2018/3/2.
//  Copyright © 2018年 cc. All rights reserved.
//  表单文字类型 cell

#import "HHFormTextFieldCell.h"
#import "HHFormSDKPublic.h"
#import "XLFormRowDescriptor.h"
#import "XLFormTextView.h"
#import "XLFormViewController.h"
#import "UIView+XLFormAdditions.h"
#import "NSObject+XLFormAdditions.h"

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wstrict-prototypes"
#import <Masonry/Masonry.h>
#pragma clang diagnostic pop


@interface HHFormTextFieldCell () <UITextFieldDelegate>
@property (nonatomic, strong) UITextField *textField;
@property (nonatomic, strong) UILabel *titleLab;
/** 单位 lb */
@property (nonatomic, strong) UILabel *unitLb;
@end

@implementation HHFormTextFieldCell
//MARK: - life cycle
+ (void)load {
    [XLFormViewController.cellClassesForRowDescriptorTypes setObject:[HHFormTextFieldCell class] forKey:HHFormRowDescriptorTypeInteger];
    [XLFormViewController.cellClassesForRowDescriptorTypes setObject:[HHFormTextFieldCell class] forKey:HHFormRowDescriptorTypeDecimal];
    [XLFormViewController.cellClassesForRowDescriptorTypes setObject:[HHFormTextFieldCell class] forKey:HHFormRowDescriptorTypeText];
    [XLFormViewController.cellClassesForRowDescriptorTypes setObject:[HHFormTextFieldCell class] forKey:HHFormRowDescriptorTypePhone];
    [XLFormViewController.cellClassesForRowDescriptorTypes setObject:[HHFormTextFieldCell class] forKey:HHFormRowDescriptorTypeLetters];
    [XLFormViewController.cellClassesForRowDescriptorTypes setObject:[HHFormTextFieldCell class] forKey:HHFormRowDescriptorTypeMail];
    [XLFormViewController.cellClassesForRowDescriptorTypes setObject:[HHFormTextFieldCell class] forKey:HHFormRowDescriptorTypePassword];
}

//MARK: - XLFormDescriptorCell
+ (CGFloat)formDescriptorCellHeightForRowDescriptor:(XLFormRowDescriptor *)rowDescriptor {
    return 50;
}
- (void) formDescriptorCellDidSelectedWithFormController:(XLFormViewController *)controller {
    if (self.rowDescriptor.action.formBlock){
        self.rowDescriptor.action.formBlock(self.rowDescriptor);
    }
    else if (self.rowDescriptor.action.formSelector){
        [controller performFormSelector:self.rowDescriptor.action.formSelector withObject:self.rowDescriptor];
    }
    else {
        if (!self.rowDescriptor.isDisabled) {
            [self.textField becomeFirstResponder];
        }
    }
}
- (void)configure {
    [super configure];
    [self setSelectionStyle:UITableViewCellSelectionStyleNone];
    [self.contentView addSubview:self.asteriskLab];
    [self.contentView addSubview:self.titleLab];
    [self.contentView addSubview:self.textField];
    [_titleLab setContentHuggingPriority:500 forAxis:UILayoutConstraintAxisHorizontal];
    [_titleLab setContentCompressionResistancePriority:1000 forAxis:UILayoutConstraintAxisHorizontal];
    
    [_titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.centerY.mas_equalTo(self.contentView);
    }];
    [self.asteriskLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(self.titleLab.mas_left).mas_offset(-1);
        make.centerY.mas_equalTo(self.contentView);
    }];
    [_textField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-15);
        make.left.mas_equalTo(self.titleLab.mas_right).mas_offset(30);
        make.centerY.mas_equalTo(self.contentView);
        make.height.mas_equalTo(40);
    }];
}
- (void)update {
    [super update];
    //*号
    self.asteriskLab.hidden = !self.rowDescriptor.required;
    //标题
    if (self.rowDescriptor.titleFont) {
        self.titleLab.font = self.rowDescriptor.titleFont;
    }
    if (self.rowDescriptor.titleColor) {
        self.titleLab.textColor = self.rowDescriptor.titleColor;
    }
    if (self.rowDescriptor.titleAlignment) {
        self.titleLab.textAlignment = self.rowDescriptor.titleAlignment;
    }
    if (self.rowDescriptor.titleWidth>0) {
        [self.titleLab mas_updateConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(self.rowDescriptor.titleWidth);
        }];
    }
    if (self.rowDescriptor.titleLeft>0) {
        [self.titleLab mas_updateConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self.rowDescriptor.titleLeft);
        }];
    }
    self.titleLab.text = self.rowDescriptor.title;
    //单位
    if (self.rowDescriptor.unit.length>0) {
        if (!_unitLb.superview) {
            [self.contentView addSubview:self.unitLb];
            [self.unitLb mas_makeConstraints:^(MASConstraintMaker *make) {
                make.right.mas_equalTo(-self.rowDescriptor.cornerInsets.right-15);
                make.centerY.mas_equalTo(self.contentView);
            }];
        }
        self.unitLb.text = self.rowDescriptor.unit;
        [self.textField mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(self.unitLb.mas_left).mas_offset(-10);
            if (self.rowDescriptor.textLeft>0) {
                //如果是固定left
                make.left.mas_equalTo(self.rowDescriptor.textLeft);
            } else {
                //默认titleLable.right+30
                make.left.mas_equalTo(self.titleLab.mas_right).mas_offset(30);
            }
            make.centerY.mas_equalTo(self.contentView);
            make.height.mas_equalTo(40);
        }];
    }
    else {
        //不展示
        [_unitLb removeFromSuperview];
        _unitLb = nil;
        [self.textField mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(-self.rowDescriptor.cornerInsets.right-15);
            if (self.rowDescriptor.textLeft>0) {
                //如果是固定left
                make.left.mas_equalTo(self.rowDescriptor.textLeft);
            } else {
                //默认titleLable.right+30
                make.left.mas_equalTo(self.titleLab.mas_right).mas_offset(30);
            }
            make.centerY.mas_equalTo(self.contentView);
            make.height.mas_equalTo(40);
        }];
    }
    //输入框
    if ([self.rowDescriptor.rowType isEqualToString:HHFormRowDescriptorTypeInteger]) {
        self.textField.keyboardType = UIKeyboardTypeNumberPad;
    }
    else if ([self.rowDescriptor.rowType isEqualToString:HHFormRowDescriptorTypeDecimal]) {
        self.textField.keyboardType = UIKeyboardTypeDecimalPad;
    }
    else if ([self.rowDescriptor.rowType isEqualToString:HHFormRowDescriptorTypeText]) {
        self.textField.keyboardType = UIKeyboardTypeDefault;
    }
    else if ([self.rowDescriptor.rowType isEqualToString:HHFormRowDescriptorTypePhone]) {
        self.textField.keyboardType = UIKeyboardTypePhonePad;
    }
    else if ([self.rowDescriptor.rowType isEqualToString:HHFormRowDescriptorTypeMail]) {
        self.textField.keyboardType = UIKeyboardTypeEmailAddress;
        self.textField.autocorrectionType = UITextAutocorrectionTypeNo;
        self.textField.autocapitalizationType = UITextAutocapitalizationTypeNone;
    }
    else if ([self.rowDescriptor.rowType isEqualToString:HHFormRowDescriptorTypePassword]) {
        self.textField.autocorrectionType = UITextAutocorrectionTypeNo;
        self.textField.autocapitalizationType = UITextAutocapitalizationTypeNone;
        self.textField.keyboardType = UIKeyboardTypeASCIICapable;
        self.textField.secureTextEntry = YES;
    }
    else if ([self.rowDescriptor.rowType isEqualToString:HHFormRowDescriptorTypeLetters]) {
        self.textField.keyboardType = UIKeyboardTypeASCIICapable;
    }
    //text 字体颜色
    if (self.rowDescriptor.textFont) {
        self.textField.font = self.rowDescriptor.textFont;
    }
    if (self.rowDescriptor.textColor) {
        self.textField.textColor = self.rowDescriptor.textColor;
    }
    if (self.rowDescriptor.textAlignment) {
        self.textField.textAlignment = [self.rowDescriptor.textAlignment intValue];
    }
    [self.textField setEnabled:!self.rowDescriptor.isDisabled];
    self.textField.textColor = self.rowDescriptor.isDisabled ? BCComConfig.config.littleBlackColor : BCComConfig.config.blackColor;
    self.textField.text = self.rowDescriptor.value ? [self.rowDescriptor displayTextValue] : self.rowDescriptor.noValueDisplayText;
    if (self.rowDescriptor.textPlaceholder) {
        _textField.placeholder = self.rowDescriptor.textPlaceholder;
    }
}
- (BOOL)formDescriptorCellCanBecomeFirstResponder {
    return (!self.rowDescriptor.isDisabled);
}
- (BOOL)formDescriptorCellBecomeFirstResponder {
    return [self.textField becomeFirstResponder];
}
- (void)highlight {
    [super highlight];
}
- (void)unhighlight {
    [super unhighlight];
    [self.formViewController updateFormRow:self.rowDescriptor];
}
- (BOOL)showBottomSplitLine {
    return YES;
}

//MARK: - UITextFieldDelegate
- (BOOL)textFieldShouldClear:(UITextField *)textField {
    return [self.formViewController textFieldShouldClear:textField];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    return [self.formViewController textFieldShouldReturn:textField];
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    return [self.formViewController textFieldShouldBeginEditing:textField];
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
    return [self.formViewController textFieldShouldEndEditing:textField];
}
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    [self.formViewController beginEditing:self.rowDescriptor];
    [self.formViewController textFieldDidBeginEditing:textField];
    // set the input to the raw value if we have a formatter and it shouldn't be used during input
    if (self.rowDescriptor.valueFormatter) {
        self.textField.text = [self.rowDescriptor editTextValue];
    }
}
- (void)textFieldDidEndEditing:(UITextField *)textField {
    // process text change before we stick a formatted value in the UITextField
    [self textFieldDidChange:textField];
    
    // losing input, replace the text field with the formatted value
    if (self.rowDescriptor.valueFormatter) {
        self.textField.text = [self.rowDescriptor.value displayText];
    }
    
    [self.formViewController endEditing:self.rowDescriptor];
    [self.formViewController textFieldDidEndEditing:textField];
}
- (void)textFieldDidChange:(UITextField *)textField {
    //长度限制，默认不限制
    int maxLength = self.rowDescriptor.textMaxLength;
    if (maxLength>0) {
        UITextInputMode *currentInputMode = textField.textInputMode;; // 键盘输入模式
        NSString *textValue = textField.text;
        if ([currentInputMode.primaryLanguage isEqualToString:@"zh-Hans"]) {
            //简体中文输入，包括简体拼音，健体五笔，简体手写
            UITextRange *selectedRange = [textField markedTextRange];
            //获取高亮部分
            UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
            // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
            if (!position) {
                if (textValue.length > maxLength) {
                    textField.text = [textValue substringToIndex:maxLength];
                }
            }
            // 有高亮选择的字符串，则暂不对文字进行统计和限制
            else{
                
            }
        } else {
            // 中文输入法以外的直接对其统计限制即可，不考虑其他语种情况
            if (textValue.length > maxLength) {
                textField.text = [textValue substringToIndex:maxLength];
            }
        }
//            if (textValue.length>self.rowDescriptor.textMaxLength) {
//                //长度超出限制，截取前面的
//                textField.text = [textValue substringToIndex:self.rowDescriptor.textMaxLength];
//            }
    }
    if ([textField.text length] > 0) {
        self.rowDescriptor.value = textField.text;
    } else {
        self.rowDescriptor.value = nil;
    }
}
#pragma mark -Getter
- (UITextField *)textField {
    if (!_textField) {
        _textField = [[UITextField alloc] init];
        _textField.delegate = self;
        _textField.borderStyle = UITextBorderStyleNone;
        _textField.clearButtonMode = UITextFieldViewModeWhileEditing;
        _textField.font = BCComConfig.config.bcFont(16);
        _textField.textColor = BCComConfig.config.blackColor;
//        _textField.bc_placeholderColor = BCComConfig.config.littleBlackColor;
        _textField.textAlignment = NSTextAlignmentRight;
        [_textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    }
    return _textField;
}
- (UILabel *)titleLab {
    if (!_titleLab) {
        _titleLab = [[UILabel alloc] init];
        _titleLab.font = BCComConfig.config.bcFont(16);
        _titleLab.textColor = BCComConfig.config.blackColor;
    }
    return _titleLab;
}
- (UILabel *)unitLb {
    if (!_unitLb) {
        _unitLb = [[UILabel alloc] init];
        _unitLb.font = BCComConfig.config.bcFont(16);
        _unitLb.textColor = kBCRGBColor(0xCCCCCC);
        _unitLb.textAlignment = NSTextAlignmentRight;
    }
    return _unitLb;
}
@end

